﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PlayingCardRecord
{
    [TemplatePart(Name = "total_row", Type = typeof(Grid))]
    public class DataGridTotal : DataGrid
    {
        DataGrid TotalRow;
        List<object> totalRowItemSource;

        //private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e)
        //{
        //   DataGridCell cell= DataGridPlus.GetRowCell(e.Row, 1);
        //    if (cell != null)
        //        cell.Content = "合计：";
        //}

        public override void OnApplyTemplate()
        {
            TotalRow = base.GetTemplateChild("TotalRow") as DataGrid;

            TotalRow.Background = new SolidColorBrush(Colors.AliceBlue);
            TotalRow.GridLinesVisibility = DataGridGridLinesVisibility.None;
            TotalRow.Visibility = Visibility.Visible;
            //TotalRow.LoadingRow += Datagrid_LoadingRow;

            int displayindex = 0;
            if (TotalRow.Columns != null)
                TotalRow.Columns.Clear();

            foreach (var item in this.Columns)
            {

                DataGridTextColumn cl = new DataGridTextColumn();
                cl.Header = item.Header;
                cl.Width = item.Width;
                cl.DisplayIndex = item.DisplayIndex = displayindex++;

                Binding widthBd = new Binding();
                widthBd.Source = item;
                widthBd.Mode = BindingMode.TwoWay;
                widthBd.Path = new PropertyPath(DataGridColumn.WidthProperty);
                BindingOperations.SetBinding(cl, DataGridTextColumn.WidthProperty, widthBd);

                Binding visibleBd = new Binding();
                visibleBd.Source = item;
                visibleBd.Mode = BindingMode.TwoWay;
                visibleBd.Path = new PropertyPath(DataGridColumn.VisibilityProperty);
                BindingOperations.SetBinding(cl, DataGridTextColumn.VisibilityProperty, visibleBd);

                Binding indexBd = new Binding();
                indexBd.Source = item;
                indexBd.Mode = BindingMode.TwoWay;
                indexBd.Path = new PropertyPath(DataGridColumn.DisplayIndexProperty);
                BindingOperations.SetBinding(cl, DataGridTextColumn.DisplayIndexProperty, indexBd);
                if(item is DataGridTextColumn)
                    cl.Binding = (item as DataGridTextColumn).Binding;


                TotalRow.Columns.Add(cl);
            }
            this.TotalRow.ItemsSource = totalRowItemSource;
            base.OnApplyTemplate();
        }

        protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            base.OnItemsSourceChanged(oldValue, newValue);

            Type itemType = null;
            totalRowItemSource = new List<object>();
            object obj = null;
            if (newValue == null)
            {
                return;
            }

            foreach (var item in newValue)
            {

                itemType = item.GetType();
                obj = Activator.CreateInstance(itemType, true);
                break;
            }
            if (itemType == null)
                return;

            PropertyInfo[] ps = itemType.GetProperties();
            foreach (var item in newValue)
            {

                foreach (PropertyInfo property in ps)
                {
                    object tmpValue = property.GetValue(item, null);
                    object totalValue = property.GetValue(obj, null);

                    if (property.PropertyType == typeof(int))
                    {
                        totalValue = (int)tmpValue + (int)totalValue;
                        property.SetValue(obj, totalValue, null);
                    }
                    else if (property.PropertyType == typeof(double))
                    {
                        totalValue = (double)tmpValue + (double)totalValue;
                        property.SetValue(obj, totalValue, null);
                    }
                }
            }
            totalRowItemSource.Add(obj);
            if (TotalRow != null)
                this.TotalRow.ItemsSource = totalRowItemSource;

        }

    }
    public static class DataGridPlus
    {
        /// <summary>
        /// 获取DataGrid控件单元格
        /// </summary>
        /// <param name="dataGrid">DataGrid控件</param>
        /// <param name="rowIndex">单元格所在的行号</param>
        /// <param name="columnIndex">单元格所在的列号</param>
        /// <returns>指定的单元格</returns>
        public static DataGridCell GetCell(this DataGrid dataGrid, int rowIndex, int columnIndex)
        {
            DataGridRow rowContainer = dataGrid.GetRow(rowIndex);
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                if (cell == null)
                {
                    dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[columnIndex]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                }
                return cell;
            }
            return null;
        }

        public static DataGridCell GetRowCell(DataGridRow rowContainer, int columnIndex)
        {
            if (rowContainer != null)
            {
                
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                if (cell == null)
                {
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                }
                return cell;
            }
            return null;
        }

        /// <summary>
        /// 获取DataGrid的行
        /// </summary>
        /// <param name="dataGrid">DataGrid控件</param>
        /// <param name="rowIndex">DataGrid行号</param>
        /// <returns>指定的行号</returns>
        public static DataGridRow GetRow(this DataGrid dataGrid, int rowIndex)
        {
            DataGridRow rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            if (rowContainer == null)
            {
                dataGrid.UpdateLayout();
                dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);
                rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            }
            return rowContainer;
        }

        /// <summary>
        /// 获取父可视对象中第一个指定类型的子可视对象
        /// </summary>
        /// <typeparam name="T">可视对象类型</typeparam>
        /// <param name="parent">父可视对象</param>
        /// <returns>第一个指定类型的子可视对象</returns>
        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }
    }

}
